#include <dirent.h>
#define IFLIST_SIZE 10000
#include "../common/dirclass.h"
#include "../common/generaldef.h"
#include "../common/utils.h"
#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;
using namespace fdutils;

void error(const char *msg){
	puts(msg);
	exit(0);
}

dir_t dir;
char infiles[IFLIST_SIZE][NAME_LEN];
char tmpline[PATH_LEN];
int ifcnt=0;

int main(int argc, char *argv[]){
	if(argc<9){
		error("Please give enough information.\narg1. directory name\narg2. input files definition\narg3. timelimit\narg4. memory limit\narg5. score\narg6. problem name\narg7. input filename\narg8. output filename");
	}
	if(!dir.open(argv[1])) error("Directory not exist.");
	FILE *finfiles=fopen(argv[2],"r");
	while(fscanf(finfiles,"%s",tmpline)!=EOF) getname(infiles[ifcnt++],tmpline);
	while(ifcnt>0 && infiles[ifcnt-1][0]==0) ifcnt--;
	fclose(finfiles);

	dir.scanentries(infiles,ifcnt);
	if(dir.filecnt()<ifcnt) error("No enough output file.");

	char filename[257]={0};
	sprintf(filename,"../dataconf.%s.lsc",argv[6]);
	FILE *fdataconf=fopen(filename,"w");
	fprintf(fdataconf,"\n");
	fprintf(fdataconf,"%cproblem %s\n",9,argv[6]);
	fprintf(fdataconf,"%c%cjudge ignore emptyline white\n",9,9);
	fprintf(fdataconf,"%c%cinput %s\n",9,9,argv[7]);
	fprintf(fdataconf,"%c%coutput %s\n",9,9,argv[8]);
	for(int i=0; i<ifcnt; i++){
		char *corr=dir.findcorr(infiles[i]);
		fprintf(fdataconf,"%c%ccase %d\n",9,9,i+1);
		fprintf(fdataconf,"%c%c%cinput %s/%s\n",9,9,9,argv[1],infiles[i]);
		fprintf(fdataconf,"%c%c%coutput %s/%s\n",9,9,9,argv[1],corr);
		fprintf(fdataconf,"%c%c%ctimelimit %s\n",9,9,9,argv[3]);
		fprintf(fdataconf,"%c%c%cmemory %s\n",9,9,9,argv[4]);
		fprintf(fdataconf,"%c%c%cscore %s\n",9,9,9,argv[5]);
	}
	fprintf(fdataconf,"end\n");
	fclose(fdataconf);
	dir.close();
	return 0;
}
